use std::sync::mpsc::{Receiver, Sender};
use specs::{world::Index, WriteStorage, System, Entities};
use crate::res::{
    observing_storage::Observing,
    minions_storage::Minions,
};

pub struct JoinMessage {
    to: Sender<Index>
}

impl JoinMessage {
    pub fn new(to: Sender<Index>) -> Self {
        JoinMessage {
            to
        }
    }
}

pub struct PlayerJoinSystem {
    rc: Receiver<JoinMessage>
}

impl PlayerJoinSystem {
    pub fn new(rc: Receiver<JoinMessage>) -> Self {
        PlayerJoinSystem {
            rc
        }
    }
}

impl<'a> System<'a> for PlayerJoinSystem {
    type SystemData = (
        Entities<'a>,
        WriteStorage<'a, Observing>,
        WriteStorage<'a, Minions>,
    );
    
    fn run(&mut self, data: Self::SystemData) {
        let (entities, mut observing, mut minions) = data;
        if let Ok(join) = self.rc.try_recv() {
            let entity = entities.create();

            observing.insert(entity, Observing(Vec::new())).unwrap();
            minions.insert(entity, Minions(Vec::new())).unwrap();

            join.to.send(entity.id()).unwrap();
        }
    }
}